package com.hp.springboot.spring.config;

import com.hp.springboot.Application;
import com.hp.springboot.result.CodeMsg;
import com.hp.springboot.result.Result;
import java.lang.reflect.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 对响应的 Result 对象进行统一处理
 *
 * @author hupan
 * @date 2021-12-17
 */
@Slf4j
@Component
@ControllerAdvice(basePackageClasses = Application.class)
public class ResponseAdvice<T> implements ResponseBodyAdvice<Result<T>> {

    @Value("${show_error_tips:false}")
    private boolean showErrorTips;

    /**
     * 对response做额外处理
     */
    @Override
    public Result<T> beforeBodyWrite(Result<T> body, MethodParameter returnType, MediaType selectedContentType,
        Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
        ServerHttpResponse response) {

        try {
            return body.setDetail("");
        } catch (Exception e) {
            log.error("返回报文处理出错", e);
            return Result.error(CodeMsg.SERVER_ERROR);
        }
    }

    /**
     * 选择哪些类，或哪些方法需要走beforeBodyWrite 从arg0中可以获取方法名和类名 arg0.getMethod().getDeclaringClass().getName()为获取方法名
     */
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        if (showErrorTips) {
            return false;
        }

        Method method = returnType.getMethod();
        return method != null && method.getReturnType() == Result.class;
    }

}